package com.sx.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author : AdinZ  1454269@qq.com
 * @Description: TODO
 * @date Date : 2019年06月19日 9:02
 **/

public class HttpService {

    private static HttpService httpService;
    private OkHttpClient client;

    public HttpService(Proxy proxy) {
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.1.3", 8888));
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS);
        if (proxy != null) builder.proxy(proxy);

        this.client = builder.build();
//                .proxy(proxy)

    }

    public static HttpService getInstance() {
        if (httpService == null) {
            synchronized (HttpService.class) {
                if(httpService==null)
                    httpService = new HttpService(null);
            }
        }
        return httpService;
    }


    public String get(String url, Map<String, Object> header) throws IOException {
        Request.Builder builder = new Request.Builder().url(url);
        if (header != null) {
            for (Map.Entry<String, Object> entry : header.entrySet()) {
                builder.header(entry.getKey(), entry.getValue() + "");
            }
        }
        return request(builder.build());
    }

    public String get(String url) throws IOException {
        return this.get(url, new HashMap<>());
    }

    public Response get(Request.Builder builder) throws IOException {
        return this.client.newCall(builder.build()).execute();
    }

    public String post(String url, Map<String, Object> post, Map<String, Object> header) throws IOException {
        Request.Builder builder = new Request.Builder().url(url);

        if (header != null) {
            for (Map.Entry<String, Object> entry : header.entrySet()) {
                builder.header(entry.getKey(), entry.getValue() + "");
            }
        }
        if (post != null) {
            StringBuffer stringBuffer = new StringBuffer();
            for (Map.Entry<String, Object> entry : post.entrySet()) {
                stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), stringBuffer.toString());
            builder.post(body);
        }

        Response response = null;
        try {
            response = this.client.newCall(builder.build()).execute();
            return response.body().string();
        } finally {
            if (response != null) response.close();
        }
    }

    public String post(String url, JSONObject post, Map<String, Object> header) throws IOException {
        Request.Builder builder = new Request.Builder().url(url);
        if (header != null) {
            for (Map.Entry<String, Object> entry : header.entrySet()) {
                builder.header(entry.getKey(), entry.getValue() + "");
            }
        }
        if (post != null) {
            RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), post.toJSONString());
            builder.post(body);
        }

        Response response = null;
        try {
            response = this.client.newCall(builder.build()).execute();
            return response.body().string();
        } finally {
            if (response != null) response.close();
        }
    }




    public String request(Request request) throws IOException {
        Response response = null;
        try {
            response = this.client.newCall(request).execute();
            return response.body().string();
        } finally {
            if (response != null) response.close();
        }
    }
    public String post(String url,String postData,String mediaType) throws IOException {
        Request.Builder builder = new Request.Builder().url(url);
        RequestBody body = RequestBody.create(MediaType.parse(mediaType), postData);
        builder.post(body);
        return request(builder.build());
    }



    public boolean download(String url, String path) throws IOException {
        File file = new File(path);
        String dirPath = path.replace(file.getAbsoluteFile().getName(), "");
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        Response response = null;
        try {
            response = this.get(new Request.Builder().url(url));
            if (response != null && response.isSuccessful()) {
                byte[] bytes = response.body().bytes();
                IOUtils.write(bytes, new FileOutputStream(file));
                return true;
            }
        } finally {
            if (response != null) response.close();
        }
        return false;
    }


}
